/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {

	owner.regs = {
		"mobile": /^1[34578]\d{9}$/
	}
	owner.config = {
		"host": "http://127.0.0.1:8088",
		"uris": {
			"auth": "/authentication/password",
			"authWithReg": "/authentication/code",
			"users": "/users",
			"sms": "/verification/code",
			"memorials": "/users/{user-id}/memorials",
		}
	}

	//local public
	owner.config.host = 'http://joker.iask.in';


	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, success, error) {
		success = success || $.noop;
		error = error || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
		if(loginInfo.mobile.length != 11 || !(owner.regs.mobile.test(loginInfo.mobile))) {
			return callback('手机号格式不正确');
		}
		if(loginInfo.password.length < 5) {
			return callback('密码最短为 5 个字符');
		}
		var users = JSON.parse(localStorage.getItem('$users') || '[]');
		var path = owner.config.host + owner.config.uris.auth
		mui.ajax(path, {
			data: {
				mobile: loginInfo.mobile,
				password: loginInfo.password
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'POST', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'Content-Type': 'application/json'
			},
			success: function(data) {
				success(JSON.stringify(data));
			},
			error: function(xhr, type, errorThrown) {
				var data = JSON.parse(xhr.response);
				error(data.message || "登陆失败，请重试");
			}
		});

	};

	/**
	 * 获取验证码
	 **/
	owner.sms = function(info, success, error) {
		success = success || $.noop;
		error = error || $.noop;
		info = info || {};
		info.mobile = info.mobile || '';
		info.code = info.code || '';

		if(info.mobile.length <= 1) {
			return error('请输入手机号');
		}

		if(!(owner.regs.mobile.test(info.mobile))) {
			return error('手机号格式不正确');
		}

		var path = owner.config.host + owner.config.uris.sms

		mui.ajax(path, {
			data: {
				mobile: info.mobile,
				code: info.code
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'POST', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'Content-Type': 'application/json'
			},
			success: function(data) {
				success("发送成功");
			},
			error: function(xhr, type, errorThrown) {
				error("发送失败，请重试");
				//异常处理；
			}
		});
	};

	/**
	 * 用户注冊
	 **/
	owner.register = function(info, success, error) {
		success = success || $.noop;
		info = info || {};
		info.mobile = info.mobile || '';
		info.code = info.code || '';

		if(info.mobile.length <= 1) {
			return error('请输入手机号');
		}

		if(!(owner.regs.mobile.test(info.mobile))) {
			return error('手机号格式不正确');
		}

		var path = owner.config.host + owner.config.uris.authWithReg

		mui.ajax(path, {
			data: {
				mobile: info.mobile,
				code: info.code
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'POST', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'Content-Type': 'application/json'
			},
			success: function(data) {
				success(data);
			},
			error: function(xhr, type, errorThrown) {
				error("注册失败，请重试");
			}
		});
	};

	owner.memorials = function(user, success, error) {
		var path = owner.config.host + owner.config.uris.memorials.replace('{user-id}', user.id);
		mui.ajax(path, {
			data: {
				"page-number": 1,
				"page-size": 100,
				"type": "ALL"
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'GET', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒;
			success: function(data) {
				success(data);
			},
			error: function(xhr, type, errorThrown) {
				error("服务器忙");
			}
		});
	}

	owner.createState = function(name, callback) {
		var state = owner.getState();
		state.account = name;
		state.token = "token123456789";
		owner.setState(state);
		return callback();
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return(email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if(!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = localStorage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	}
	/**
	 * 获取本地是否安装客户端
	 **/
	owner.isInstalled = function(id) {
		if(id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if(mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch(e) {}
		} else {
			switch(id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
}(mui, window.app = {}));